/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ChateoController;

import ChateoNI.*;
import ChateoFacadeNI.*;
import ChateoFacadeGUI.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author abdala
 */
public class Controller {
    
    //The list of user where each user is defined by an id you can find in its own class
    private UsersList userList = new UsersList();
    //The list of messages where each message is defined by an id you can find in its own class
    private ArrayList<ChatMessage> messageList = new ArrayList<ChatMessage>();
    //The debugging state will provide some more verbose
    private static boolean debug=true;
    //Login of the user
    private String myLogin = "Olga";
    //Facades
    private FacadeGUI facadegui;
    private FacadeNI facadeni;
    //IDs for a user
    InetAddress addr;
    String login;
 
    User LoggedInUser = new User(addr,login, true);
    User LoggedOutUser = new User(addr,login, false);
    User theNewOne;
    /* @pa
     * 
     * 
     */
    public String newUser(String remoteLogin,InetAddress remoteAddr) throws UnknownHostException{
        String out = "";
        
        //We check if the user doesn't already exist in our user list.
        //Ne pas créer un user tant qu'on n'a pas vérifié s'il existe ou pas
        if(userList.contains(LoggedInUser)){
            System.err.println("The user " +LoggedInUser.getLogin()+ " already exists in the list.Please enter a new login");
            System.exit(-1);
        }
        else if(userList.contains(LoggedOutUser)){
            //We create a new user
            theNewOne = new User(remoteAddr, remoteLogin);
        }
                
        //Now, the goal is to add him to the list
        userList.add(theNewOne);
        try {
            //userList.add(theNewOne.getId(),theNewOne);
            //Send the ACK to the user that just got connected with our ID
            sendAck(myLogin,InetAddress.getLocalHost());
        } catch (SocketException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
        //Once the user is added to the userlist we can change his state to Logged In
        userList.get(userList.indexOf(LoggedOutUser)).setLoggingState(true);
        
        //GUI Update
        // TODO WHEN THE GUI WILL BE READY
        //
        
        if (DebugMode()){
            System.out.println("User: " +userList.get(userList.indexOf(LoggedOutUser)) + "has been added to the user List");
            out=remoteLogin;
        }
        else{
            out=remoteLogin;
        }
        return out;
    }

    
    
    public void sendAck(String login,InetAddress IPaddr) throws UnknownHostException, SocketException{
        //TODO : 
        // 
        //-Lancer la methode de la facade qui envoie le ACK
        facadeni.outgoingAck(IPaddr, login);
        //
    }
    //This method is to check if a user has just left
    
   //public String userLeft(String login, InetAddress IPaddr){
    public boolean userLeft(){
        //String out="";
        //TODO : 
        //-Utiliser la recherche dans userlist par Login et IP
          if(!userList.contains(LoggedInUser)){
              //-Changer le status de l'user
            userList.get(userList.indexOf(LoggedInUser)).setLoggingState(false);
            System.out.println("The user " +LoggedInUser.getLogin()+ " has left");
        }
        //-Effectuer la MAJ du GUI
        //return out;
          return true;
        
    }

    public String getMyLogin() {
        return myLogin;
    }
    
    public static void main(String[] args) throws Exception {
        
        int serv = 0;   //Client by default
        if(serv == 1){
            ConnexionUDPServer server=new ConnexionUDPServer();
            server.start();
        }
        else{
            ConnexionUDPClient client=new ConnexionUDPClient();
            //A client sends a "hello" msg in bcast to notify everybody,that (s)he is connected
            String adr="255.255.255.255";
            InetAddress iAdr = InetAddress.getByName(adr);
            client.sendMessage(iAdr, new Hello("toto",false));
            System.out.println("The client has been successfully connected. \n");
        }
        
    }
    public static boolean DebugMode() {
        return debug;
    }
    
}